package algotithm.leetcode.tree.test103;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/13-22:55
 * @URL https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
 * @Title 103. 二叉树的锯齿形层序遍历
 */
public class Solution {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> q = new ArrayDeque<>();
        if (root == null) {
            return res;
        }
        q.add(root);
        boolean flag = true;
        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> list = new ArrayList<>();
            while (size-- > 0) {
                TreeNode node = q.poll();
                if (flag) {
                    list.add(node.val);
                } else {
                    list.add(0,node.val);
                }
                if (node.left != null) {
                    q.add(node.left);
                }
                if (node.right != null) {
                    q.add(node.right);
                }
            }
            flag = !flag;
            res.add(list);
        }
        return res;
    }

}
